package main

import (
    "fmt"
    "net"
    "time"
)

func main() {
    go startMaster()
    go startSlave()

    fmt.Println("Master and Slave started. Press Ctrl+C to exit.")
    select {}
}

func startMaster() {
    listener, err := net.Listen("tcp", ":8080")
    if err != nil {
        fmt.Println("Master: Error starting listener:", err)
        return
    }
    defer listener.Close()

    fmt.Println("Master: Listening on :8080")

    for {
        conn, err := listener.Accept()
        if err != nil {
            fmt.Println("Master: Error accepting connection:", err)
            continue
        }
        go handleConnection(conn)
    }
}

func handleConnection(conn net.Conn) {
    defer conn.Close()

    for {
        message := "Hello from Master"
        _, err := conn.Write([]byte(message))
        if err != nil {
            fmt.Println("Master: Error sending message:", err)
            return
        }

        time.Sleep(2 * time.Second)
    }
}

func startSlave() {
    conn, err := net.Dial("tcp", "localhost:8080")
    if err != nil {
        fmt.Println("Slave: Error connecting to master:", err)
        return
    }
    defer conn.Close()

    fmt.Println("Slave: Connected to master")

    buffer := make([]byte, 1024)
    for {
        n, err := conn.Read(buffer)
        if err != nil {
            fmt.Println("Slave: Error reading message:", err)
            return
        }

        message := string(buffer[:n])
        fmt.Println("Slave: Received message:", message)
    }
}
